import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/reports.dart';
import 'package:ichinesereader/models/forms/forms.dart';
import 'package:ichinesereader/models/report/studentActivityDto.dart';
import 'package:ichinesereader/pages/common/report/reportsStudentPersonalContent.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/grids/studentActivityDataGrid.dart';
import 'package:reactive_dropdown_search/reactive_dropdown_search.dart';
import 'package:reactive_forms/reactive_forms.dart';

import '../../../themes/appTheme.dart';

class ReportsStudentPersonalActivity extends StatefulWidget {
  ReportsStudentPersonalActivity({
    Key? key,
    required this.classId,
    required this.userName,
  }) : super(key: key);
  final String classId;
  final String userName;

  @override
  ReportsStudentPersonalActivityState createState() =>
      ReportsStudentPersonalActivityState();
}

class ReportsStudentPersonalActivityState
    extends State<ReportsStudentPersonalActivity> {
  final ReportsController _reportsController = Get.find();
  var box = Hive.box('appconfig');
  final formModel = ActivityRequestModel();
  late FormGroup form;
  //int initDayNum = 15;

  StudentActivityDto dto = new StudentActivityDto(
      from: DateTime.now().add(Duration(days: -1 * 15)).millisecondsSinceEpoch,
      to: DateTime.now().millisecondsSinceEpoch);

  @override
  void initState() {
    studentPersonalReportTab = Constants.studentPersonalReportTabs[2];

    if (_reportsController.studentActivity.value.list != null) {
      _reportsController.studentActivity.value.list?.clear();
    }
    form = this.formModel.form;
    form.control('past').value = 15;
    form.control('activity').value = <String>[];
    form.control('entry').value = <String>[];

    fetchOverallData(widget.classId, widget.userName, dto);

    super.initState();
  }

  void _onCustomTimeUpdate() {
    if (!form.valid) {
      form.markAllAsTouched();
      return;
    }

    int pastVal = form.control("past").value;

    List<String> selectedActivity = form.control("activity").value;
    List<String> selectedEntry = form.control("entry").value;
    var tempDto = new StudentActivityDto(
        activities: selectedActivity
            .map((val) => Constants.activities
                .firstWhere((x) => x.label == val)
                .value
                .toString())
            .toList(),
        entry: selectedEntry
            .map((val) => Constants.entries
                .firstWhere((x) => x.label == val)
                .value
                .toString())
            .toList(),
        from: pastVal == 0
            ? null
            : DateTime.now()
                .add(Duration(days: -pastVal))
                .millisecondsSinceEpoch,
        to: pastVal == 0 ? null : DateTime.now().millisecondsSinceEpoch);
    setState(() {
      dto = tempDto;
    });

    fetchOverallData(widget.classId, widget.userName, tempDto);
  }

  void fetchOverallData(classId, userName, tempDto) {
    Future.delayed(Duration(milliseconds: 100), () {
      _reportsController.fetchStudentActivity(classId, userName, tempDto);
    });
  }

  void resetForm() {
    StudentActivityDto dto = new StudentActivityDto(
        from:
            DateTime.now().add(Duration(days: -1 * 15)).millisecondsSinceEpoch,
        to: DateTime.now().millisecondsSinceEpoch);
    setState(() {
      dto = dto;
    });
    form.control('past').value = 15;
    form.control('activity').value = <String>[];
    form.control('entry').value = <String>[];
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build SchoolAdmin reportsStudentPersonal activity');
    final isSmallScreen =
        MediaQuery.of(context).size.width < Constants.DefinedScreenSmallSize;
    return Center(
        child: Padding(
      padding: const EdgeInsets.all(10),
      child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
        Row(
          children: [
            Expanded(
              child: ReactiveForm(
                  formGroup: form,
                  child: Column(children: [
                    isSmallScreen
                        ? Column(
                            children: <Widget>[
                              Container(
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(3.0),
                                  color: Colors.white.withOpacity(0.3),
                                ),
                                padding: EdgeInsets.symmetric(horizontal: 21.0),
                                child: ReactiveDropdownField<dynamic>(
                                  dropdownColor: Get.isDarkMode
                                      ? AppTheme.colors.darkTheme2
                                      : Get.theme.primaryColor,
                                  formControlName: 'past',
                                  decoration: InputDecoration(
                                      labelText: 'Choose Date Period'.tr,
                                      labelStyle: TextStyle(
                                          color: Get.isDarkMode
                                              ? Colors.white
                                              : Colors.black)),
                                  onChanged: (value) => form
                                      .control('past')
                                      .value = value.value as int,
                                  items: Constants.timeRangesWithoutCustom
                                      .map((value) {
                                    return DropdownMenuItem(
                                      value: value.value as int,
                                      child: Text(
                                        value.label.toString(),
                                        style: Theme.of(context)
                                            .textTheme
                                            .titleSmall
                                            ?.copyWith(
                                                color: Get.isDarkMode
                                                    ? Get.theme.primaryColorDark
                                                    : Colors.white),
                                        overflow: TextOverflow.fade,
                                      ),
                                    );
                                  }).toList(),
                                ),
                              ),
                              Container(
                                margin: EdgeInsets.symmetric(vertical: 12.0),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(3.0),
                                  color: Colors.white.withOpacity(0.3),
                                ),
                                padding: EdgeInsets.symmetric(horizontal: 21.0),
                                //没有改颜色的选项
                                child: ReactiveDropdownSearchMultiSelection<
                                    String, String>(
                                  formControlName: 'activity',
                                  dropdownDecoratorProps:
                                      DropDownDecoratorProps(
                                    dropdownSearchDecoration: InputDecoration(
                                      hintText: "Activities".tr,
                                    ),
                                  ),
                                  popupProps: PopupPropsMultiSelection.menu(
                                      showSelectedItems: true),
                                  items: Constants.activities
                                      .map((x) => x.label!)
                                      .toList(),
                                  showClearButton: true,
                                ),
                              ),
                              Container(
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(3.0),
                                  color: Colors.white.withOpacity(0.3),
                                ),
                                padding: EdgeInsets.symmetric(horizontal: 21.0),
                                child: ReactiveDropdownSearchMultiSelection<
                                    String, String>(
                                  formControlName: 'entry',
                                  dropdownDecoratorProps:
                                      DropDownDecoratorProps(
                                    dropdownSearchDecoration: InputDecoration(
                                      hintText: "Locations".tr,
                                    ),
                                  ),
                                  popupProps: PopupPropsMultiSelection.menu(
                                    showSelectedItems: true,
                                  ),
                                  items: Constants.entries
                                      .map((x) => x.label!)
                                      .toList(),
                                  showClearButton: true,
                                ),
                              ),
                              Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceAround,
                                  children: [
                                    Padding(
                                      padding: const EdgeInsets.only(top: 30.0),
                                      child: ReactiveFormConsumer(
                                        builder: (context, form, child) {
                                          return ElevatedButton(
                                              style: ButtonStyle(
                                                minimumSize:
                                                    MaterialStateProperty.all(
                                                        const Size(300, 60)),
                                              ),
                                              child: Text('Go'.tr),
                                              onPressed: _onCustomTimeUpdate);
                                        },
                                      ),
                                    ),
                                  ])
                            ],
                          )
                        : Column(
                            children: [
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceAround,
                                children: <Widget>[
                                  Flexible(
                                    child: Padding(
                                      padding:
                                          const EdgeInsets.only(right: 21.0),
                                      child: Container(
                                        decoration: BoxDecoration(
                                          borderRadius:
                                              BorderRadius.circular(3.0),
                                          color: Colors.white.withOpacity(0.3),
                                        ),
                                        padding: EdgeInsets.symmetric(
                                            horizontal: 21.0),
                                        child: ReactiveDropdownField<dynamic>(
                                          dropdownColor: Get.isDarkMode
                                              ? AppTheme.colors.darkTheme2
                                              : Get.theme.primaryColor,
                                          formControlName: 'past',
                                          decoration: InputDecoration(
                                              labelText:
                                                  'Choose Date Period'.tr,
                                              labelStyle: TextStyle(
                                                  color: Get.isDarkMode
                                                      ? Colors.white
                                                      : Colors.black)),
                                          onChanged: (value) => form
                                              .control('past')
                                              .value = value.value as int,
                                          items: Constants
                                              .timeRangesWithoutCustom
                                              .map((value) {
                                            return DropdownMenuItem(
                                              value: value.value as int,
                                              child: Text(
                                                value.label.toString(),
                                                style: Theme.of(context)
                                                    .textTheme
                                                    .titleSmall
                                                    ?.copyWith(
                                                        color: Get.isDarkMode
                                                            ? Get.theme
                                                                .primaryColorDark
                                                            : Colors.white),
                                                overflow: TextOverflow.fade,
                                              ),
                                            );
                                          }).toList(),
                                        ),
                                      ),
                                    ),
                                  ),
                                  Flexible(
                                    child: Padding(
                                      padding: const EdgeInsets.symmetric(
                                          horizontal: 21.0),
                                      child: Container(
                                        decoration: BoxDecoration(
                                          borderRadius:
                                              BorderRadius.circular(3.0),
                                          color: Colors.white.withOpacity(0.3),
                                        ),
                                        padding: EdgeInsets.symmetric(
                                            horizontal: 21.0),
                                        child:
                                            ReactiveDropdownSearchMultiSelection<
                                                String, String>(
                                          formControlName: 'activity',
                                          dropdownDecoratorProps:
                                              DropDownDecoratorProps(
                                            dropdownSearchDecoration:
                                                InputDecoration(
                                              hintText: "Activities".tr,
                                            ),
                                          ),
                                          popupProps:
                                              PopupPropsMultiSelection.menu(
                                                  showSelectedItems: true),
                                          items: Constants.activities
                                              .map((x) => x.label!)
                                              .toList(),
                                          showClearButton: true,
                                        ),
                                      ),
                                    ),
                                  ),
                                  Flexible(
                                    child: Padding(
                                      padding:
                                          const EdgeInsets.only(left: 21.0),
                                      child: Container(
                                        decoration: BoxDecoration(
                                          borderRadius:
                                              BorderRadius.circular(3.0),
                                          color: Colors.white.withOpacity(0.3),
                                        ),
                                        padding: EdgeInsets.symmetric(
                                            horizontal: 21.0),
                                        child:
                                            ReactiveDropdownSearchMultiSelection<
                                                String, String>(
                                          formControlName: 'entry',
                                          dropdownDecoratorProps:
                                              DropDownDecoratorProps(
                                            dropdownSearchDecoration:
                                                InputDecoration(
                                              hintText: "Locations".tr,
                                            ),
                                          ),
                                          popupProps:
                                              PopupPropsMultiSelection.menu(
                                            showSelectedItems: true,
                                          ),
                                          items: Constants.entries
                                              .map((x) => x.label!)
                                              .toList(),
                                          showClearButton: true,
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                              Row(
                                  mainAxisAlignment: MainAxisAlignment.end,
                                  children: [
                                    Padding(
                                      padding: const EdgeInsets.only(top: 12.0),
                                      child: ReactiveFormConsumer(
                                        builder: (context, form, child) {
                                          return ElevatedButton(
                                              style: ButtonStyle(
                                                minimumSize:
                                                    MaterialStateProperty.all(
                                                        const Size(90, 60)),
                                              ),
                                              child: Text('Go'.tr),
                                              onPressed: _onCustomTimeUpdate);
                                        },
                                      ),
                                    ),
                                  ])
                            ],
                          ),
                  ])),
            ),
          ],
        ),
        Expanded(child: _reportsController.obx((data) {
          if (_reportsController.studentActivity.value.list != null) {
            return StudentActivityDataGrid(
                _reportsController.studentActivity.value.list!);
          } else {
            return Text('');
          }
        })),
      ]),
    ));
  }
}
